process.env.TZ = 'Asia/Shanghai';

fs = require('fs');
// mysql = require('mysql');

http = require('http');

var uim = require('./uim.js');

constains = require('constants');

var qs = require('querystring');
const urlLib = require('url');//处理url相关

// 环境配置（以下划线开头的配置表示允许在运行中重新赋值并立即生效）
const ENV = {
    AREA_ID: fs.readFileSync('./.env/AREA_ID', 'utf-8').trim(), // 服务器分区编号
    LISTEN_PORT: fs.readFileSync('./.env/LISTEN_PORT', 'utf-8').trim(),
    REDIS: {
        PORT: fs.readFileSync('./.env/redis.port', 'utf-8').trim(),
        HOST: fs.readFileSync('./.env/redis.host', 'utf-8').trim(),
        PASSWORD: fs.readFileSync('./.env/redis.password', 'utf-8').trim(),
    },
    _DEBUG_MODE: true,
}

console.log(ENV);

var redis = require('redis');
const { send } = require('process');
const { SSL_OP_SSLEAY_080_CLIENT_DH_BUG } = require('constants');

// 用于连接控制台redis，与其他服务保持通信，接收事件消息
var console_redis_sub = undefined;

// 用于连接控制台redis，与其他服务保持通信，发出广播事件
var console_redis_pub = redis.createClient(ENV.REDIS.PORT, ENV.REDIS.HOST, { auth_pass: ENV.REDIS.PASSWORD });
console_redis_pub.on('ready', function (err) {
    // 如果连接控制台失败
    if (err) {
        throw 'pub连接控制台失败'
    } else {
        console.log('pub已连接到控制台');
        init_porject_list(); // 初始项目列表
    }
});
var init_redis_subscribe = function () {
    console_redis_sub = redis.createClient(ENV.REDIS.PORT, ENV.REDIS.HOST, { auth_pass: ENV.REDIS.PASSWORD });
    console_redis_sub.on('ready', function (err) {
        // 如果连接控制台失败
        if (err) {
            throw 'sub连接控制台失败'
        } else {
            console.log('sub已连接到控制台');
        }
    });
    console_redis_sub.subscribe('console'); // 订阅控制台信息
    console_redis_sub.on('subscribe', function (channel, count) {
        console.log(`got subscribe event: ${channel} and count is ${count}`);
    });
    console_redis_sub.on('connect', function () {
        //订阅客户端接收到消息
        console_redis_sub.on('message', function (channel, message) {
            var time = new Date().getTime();
            var response = `${time} received message from ${channel}:${message}`;
            // console.log(response);
            switch (channel) {
                case 'console':
                    // some code
                default:
                    break;
            }
        });
        console.log('uim-console已就绪');

    });
}
function getClientIp(req) {
    return req.headers['x-forwarded-for'] ||
        req.connection.remoteAddress ||
        req.socket.remoteAddress ||
        req.connection.socket.remoteAddress;
};
var app = http.createServer( function (req, res) {
    res.writeHead(200, {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
    });
    //GET
    var obj = urlLib.parse(req.url, true);
    var url = obj.pathname;
    const GET = obj.query;

    //POST
    var str = '';
    var POST = '';
    req.on('data', function (data) {
        str += data;
    });
    req.on('end', function () {
        POST = qs.parse(str);
        console.log({ req_url: req.url, url, GET, POST });

        // var url = req.url.split('?')[0];
        switch (url) {
            case '/api':
                break;

            default:
                res.end('{"status":"ERROR"}');
                break;
        }
    });
}).listen(ENV.LISTEN_PORT);
var io = require('socket.io').listen(app);
io.sockets.on('connection', function (socket) {
    online_client_number++;
    console.log(uim.dateTime() + ' - 客户端连接：' + socket.request.connection.remoteAddress + '。在线总人数：' + online_client_number + '。socket.id：' + socket.id);
    

    //调试
    socket.on('debug', function (debug_code) {
        console.log('debug: ' + debug_code);
        //此调试方法只在调试模式下使用
        if (ENV._DEBUG_MODE) eval(debug_code);
    });

    socket.on('disconnect', function (data) {
        online_client_number--;
        console.log(uim.dateTime() + ' - 客户端断开：' + socket.request.connection.remoteAddress + '。在线总人数：' + online_client_number + '。socket.id：' + socket.id);
    });
});

console.log('uim console is running: ' + uim.dateTime());